import { sqlQuery } from "../db/resetSet/index";
import type { UserFace } from "@/types/user";
import jwt from "jsonwebtoken";
const tableName = `xh_admin_user`;

export const list = () => {
  return new Promise((resolve, reject) => {
    const sql = `SELECT * FROM ${tableName}`;
    sqlQuery(sql).then((res) => {
      resolve(res);
    });
  });
};

export const info = (userId: string): Promise<UserFace> => {
  return new Promise((resolve, reject) => {
    const sql = `SELECT * FROM xh_admin_user where id=${userId}`;
    sqlQuery(sql).then((res) => {
      resolve(res[0]);
    });
  });
};
export const add = (option: UserFace): Promise<UserFace> => {
  const { username, password } = option;

  return new Promise((resolve, reject) => {
    const query = `INSERT INTO xh_admin_user (id, username, nickname, password) VALUES(null, '${username}' , '2334','${password}');`;

    console.log(query);
    sqlQuery(query).then((res) => {
      resolve(res);
    });
  });
};
type IWheres = ([string, string, any] | string)[] | string;
const getWhere = (arr: IWheres) => {
  let strArr: string[] = [];
  if (typeof arr === "string") {
    return arr;
  }
  arr.forEach((item, index) => {
    if (typeof item === "string") {
      strArr.push(item);
      return;
    }
    let str = "";
    const [key, symbol, val] = item;
    strArr.push(`${key} ${symbol} '${val}'`);
  });
  return strArr.join(" and ");
};

export const login = (option: UserFace): Promise<UserFace> => {
  const { username, password } = option;
  let where: IWheres = [];
  where.push(["username|phone|email", "=", username]);
  where.push(["password", "=", password]);
  where.push(["is_delete", "=", 0]);
  console.log(where);
  let whereStr = getWhere(where);

  console.log(whereStr);
  return new Promise((resolve, reject) => {
    const query = `SELECT id FROM xh_admin_user WHERE ${whereStr}`;
    console.log(query);
    sqlQuery(query).then((res) => {
      resolve(res[0]);
    });
  });
};
